export default {
    ws: null,
    closeWebSocket: function() {
        if (this.ws) {
            this.ws.close()
        }
    },
    initWebSocket: function(token, onmessageCallback) {
        var that = this;
        if ('WebSocket' in window && window.HC_config.VUE_APP_WEBSOCKET_BASE_URL) {
            // console.log("您的浏览器支持 WebSocket!");
            // location.host
            // this.ws = new WebSocket(window.Define.PROJECT[window.Define.DEFAULT_PROJECT].VUE_APP_WEBSOCKET_BASE_URL + '/message/websocket/token' + token)
            this.ws = new WebSocket(window.HC_config.VUE_APP_WEBSOCKET_BASE_URL + '/message/websocket/token' + token)
            this.ws.onopen = function() {
                console.log('websocket连接成功')
            };

            this.ws.onmessage = function(res) {
                console.log('收到服务器内容', res);
                if (res.data) {
                    var obj = JSON.parse(res.data);
                    if (obj) {
                        onmessageCallback(obj)
                    }
                }
            };

            this.ws.onclose = function() {
                // 关闭 websocket
                console.log('连接已关闭...');
                //  断线重新连接
                setTimeout(() => {
                    that.initWebSocket(token, onmessageCallback)
                }, 2000)
            }
        } else {
            // 浏览器不支持 WebSocket
            console.log('您的浏览器不支持 WebSocket!')
        }
    }
}
